from django.shortcuts import render

from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
import logger
from user.admin import User,Project,Book,Author,ItemTrade,acount
from .models import Student,Course
import base64
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage  # 分页用到的3个模块
from django.db.models import Max
# Create your views here.

import string,random
from django.core.signing import Signer
from django.core.cache import cache
from datetime import timedelta

# 或的查询需要导入的模块:
from django.db.models import Q,Max,Min,Count,Avg,Sum

# 判空方法:
def is_empty(c):
    return c is None or str(c).strip()==''

# 为密码加密的方法
def b64encodec(c):
    # 先把这个字符串转成字节码
    bc=bytes(c,encoding='utf-8')
    b64c=base64.b64encode(bc).decode('utf-8')
    return b64c

# 提token值
def createtoken(name):
    # 首先是产生一个8位的随机字符串(a-zA-z)
    logger.logger.info(f'看看这个ascii_letter是什么内容:{string.ascii_letters}')
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    logger.logger.info(f'看看这个random随机字符串是什么内容:{randomstr}')
    # 产生token
    token=Signer().sign(randomstr+name)
    # 把这个token设置到服务器的缓存中
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    # 返回这个token
    return token

# 鉴权
def checktoken(request):
    # 从前端的请求中获取token内容
    logger.logger.info(f"request.META是什么内容:{request.META}")
    reqtoken=request.META.get('HTTP_TOKEN')
    logger.logger.info(f"reqtoken长什么样子:{reqtoken}")
    # 如果前段没有传token,会进行下面这个分支
    if reqtoken is None:
        return False,'XXXXX'
    # 对获取到的token,进行反签名
    untoken=Signer().unsign(reqtoken)
    logger.logger.info(f"饭签名后的内容：{untoken}")
    # 从反签名后的内容获取用户名name
    name=untoken[8:]
    # 从缓存中获取token
    cachetoken=cache.get(f'test_{name}')
    # 如果进入下面这个分支，说明缓存中的token已经过期了，不存在了
    if cachetoken is None:
        return False,'XXXXX'
    # 如果缓存中的token还存在
    return True,name

# 登录
@api_view(['GET'])
def login(request):
    # data=JSONParser().parse(request)
    # logger.logger.info(f'看看data:{data}')
    logger.logger.info(f'看看request.GET:{request.GET}')

    name=request.GET.get("name")
    password=request.GET.get("password")

    # 判空的校验
    if is_empty(name) or is_empty(password):
        return JsonResponse({
            'msg':"必填项不可为空"
        },status=400)
    if User.objects.filter(name=name).exists() is False:
        return JsonResponse({
            'msg':"用户不存在"
        },status=400)
    # 把用户对象查询出来
    obj=User.objects.get(name=name)
    # 加密密码
    b64password=b64encodec(password)
    if obj.password == b64password:
        # 产生token
        token=createtoken(name)
        return JsonResponse({
            'msg':"登录成功",
            "token":token
        })
    else:
        return JsonResponse({
            'msg':"密码错误",
        },status=409)

# 视图函数添加
@api_view(['POST'])
def adduser(request):

    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg':"未登录"
        })

    logger.logger.info(f'看看获得的request是什么样子:{request}')
    data = JSONParser().parse(request)
    logger.logger.info(f'看看获得的data是什么样子:{data}')


    name=data.get('name')
    password=data.get('password')
    gender=data.get('gender')
    age=data.get('age')

    # 为空的判断
    if is_empty(name) or is_empty(password) or is_empty(gender) or is_empty(age):
        return JsonResponse({
            'msg':"必填项参数不能为空"
        },status=400)

    # 判重
    if User.objects.filter(name=name).exists():
        return JsonResponse({
            'msg':"用户名已存在"
        },status=409)



    # 向数据表插入数据
    try:
        b64password=b64encodec(password)
        User(name=name,password=b64password,gender=gender,age=age).save()

        return JsonResponse({
            'msg':"添加用户成功"
        })
    except Exception as e:
        return JsonResponse({
            'msg':"服务端内部错误"
        },status=500)


# 6.23日考添加
@api_view(['POST'])
def addproject(request):
    data=JSONParser().parse(request)
    project_name=data.get('project_name')
    start_time=data.get('start_time') #2025-06-23
    end_time=data.get('end_time') #2025-06-23
    status=data.get('status')
    create_time=data.get('create_time')
    user_id=data.get('user_id')

    if is_empty(project_name) or is_empty(start_time) or is_empty(end_time) or is_empty(status) or is_empty(user_id):
        return JsonResponse({
            'msg':"必填项不可为空"
        })

    if Project.objects.filter(user_id=user_id).exists():
        return JsonResponse({
            'msg':"用户id不可重复"
        },status=400)

    try:
        Project(user_id=user_id,project_name=project_name,start_time=start_time,end_time=end_time,status=status,create_time=create_time).save()
        return JsonResponse({
            'msg':"添加用户成功"
        })
    except Exception as e:
        print(e)
        return JsonResponse({
            'msg':"服务器内部错误"
        },status=500)

# 6.26周考添加
# 添加
@api_view(['POST'])
def addTrade(request):
    logger.logger.info(f'看看这个request是什么样子:{request}')
    data=JSONParser().parse(request)
    logger.logger.info(f'看看这个data是什么样子:{data}')

    item_id=data.get('item_id')
    title=data.get('title')
    price=data.get('price')
    seller_name=data.get('seller_name')
    is_available=data.get('is_available')

    if is_empty(title) or is_empty(price) or is_empty(seller_name):
        return JsonResponse({
            'msg':"必填项参数不可为空"
        },status=400)
    try:
        ItemTrade(item_id=item_id,title=title,price=price,seller_name=seller_name,is_available=is_available).save()
        allobj=ItemTrade.objects.filter()
        lis=[]
        for item in allobj:
            lis.append({
                '标识物品':item.item_id,
                '物品标题':item.title,
                '物品价格':item.price,
                '卖家姓名':item.seller_name,
                '物品是否可售':item.is_available,
            })
        return JsonResponse({
            'msg':"添加成功",
            'item_id':lis
        },status=200)
    except Exception as e:
        return JsonResponse({
            'msg':"服务器内部错误",
            'data':e,
        },status=500)
# 6.26周考更新
@api_view(['POST'])
def upateattributes(request):
    data=JSONParser().parse(request)
    attributes=data.get('attributes')
    item_id=data.get('item_id')
    update_all=data.get('update_all')

    if is_empty(item_id):
        return JsonResponse({
            'msg':"物品id不能为空"
        },status=400)
    if is_empty(attributes):
        return JsonResponse({
            'msg': "属性不能为空，无法执行空更新操作"
        },status=400)
    if ItemTrade.objects.filter(item_id=item_id).exists() is False:
        return JsonResponse({
            'msg':"物品不存在"
        },status=400)
    obj=ItemTrade.objects.get(item_id=item_id)
    if update_all=="True":
        for key,value in attributes.items():
            setattr(obj,key,value)
            # obj.key=value
        # obj.title=attributes.get("title")
        # obj.seller_name=attributes.get("seller_name")
        #
        obj.save()
    else:
        for key,value in attributes.items():
            setattr(obj, key, value)
        #     obj.key=value
        # obj.title = attributes.get("title")
        # obj.seller_name = attributes.get("seller_name")

        obj.save()
    return JsonResponse({
        'msg':"修改成功",
        'item_id':obj.item_id,
        'title':obj.title,
        'price':obj.price,
        'seller_name':obj.seller_name,
        'is_available':obj.is_available,
    })


# 添加书籍
@api_view(['POST'])
def addbook(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    price=data.get('price')
    category=data.get('category')
    pubishdata=data.get('pubishdata')
    pubisher=data.get('pubisher')
    # 穿过来作者id:(authorid)
    authorid=data.get('authorid')
    # creaetime=data.get('creaetime')
    # updatetime=data.get('updatetime')

    # Book(name=name,price=price,category=category,pubishdata=pubishdata,pubisher=pubisher,author_id=authorid).save()
    authorobj=Author.objects.get(id=authorid)
    Book(name=name,price=price,category=category,pubishdata=pubishdata,pubisher=pubisher,author=authorobj).save()

    return JsonResponse({
        'msg':"添加书籍成功"
    })


# VUE添加注册
@api_view(['POST'])
def zhuce(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    password=data.get('password')
    b64password=b64encodec(password)
    logger.logger.info(f'看看b64password:{b64password}')
    acount(name=name,password=b64password).save()

    return JsonResponse({
        'msg':"添加成功",
    })
# VUE登录方法
@api_view(['GET'])
def Vue_login(request):
    name=request.GET.get('name')
    password=request.GET.get('password')
    b64password = b64encodec(password)

    if acount.objects.filter(name=name).exists() is False:
        return JsonResponse({
            'msg':"账号不存在"
        },status=404)
    obj = acount.objects.get(name=name)
    logger.logger.info(f'看看get查询到的对象:{obj}')
    if obj.password==b64password:
        token=createtoken(name)
        return JsonResponse({
            'msg':"登录成功",
            'token':token
        })
    else:
        return JsonResponse({
            'msg':"密码错误"
        },status=400)
# 条件查询下拉菜单
@api_view(['GET'])
def getpublishervue(request):
    publisherdata=Book.objects.values('pubisher').annotate(publishername=Max('pubisher'))
    logger.logger.info(f'获取到的数据:{publisherdata}')
    list=[{'label':"请选择",'value':""}]
    for item in publisherdata:
        list.append({
            'label':item.get('pubisher'),
            'value':item.get('pubisher')
        })
    return JsonResponse({
        'msg':'查询成功',
        'data':list
    })

# VUE显示与分页列表
@api_view(['GET'])
def get_book_list(request):
    page=request.GET.get('_page')
    pagesize=request.GET.get('_per_page')

    name=request.GET.get('name')
    authorname=request.GET.get('authorname')
    pubisher=request.GET.get('pubisher')
    dic={}
    if is_empty(name) is False:
        dic['name']=name
    if is_empty(pubisher) is False:
        dic['pubisher']=pubisher
    if is_empty(authorname) is False:
        if Author.objects.filter(name=authorname).exists():
            obj=Author.objects.get(name=authorname)
            dic['author_id']=obj.id
        else:
            dic['author_id']=-1


    allobj=Book.objects.filter(**dic)
    pageobj=Paginator(allobj,pagesize)
    try:
        singobj=pageobj.page(page)
    except PageNotAnInteger:
        singobj=pageobj.page(1)
    except EmptyPage:
        singobj=pageobj.page(pageobj.num_pages)
    lis=[]
    for item in singobj.object_list:
        lis.append({
            'id':item.id,
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'pubishdata':item.pubishdata,
            'pubisher':item.pubisher,
            'author':item.author.name,
            'creaetime':item.creaetime,
            'updatetime':item.updatetime,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis,
        'items':allobj.count()
    })
# vue添加数据到列表中
@api_view(['POST'])
def add_book_vue(request):
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg':"未登录，请先登录"
        },status=401)

    data=JSONParser().parse(request)
    name=data.get('name')
    price=data.get('price')
    category=data.get('category')
    pubishdata=data.get('pubishdata')
    pubisher=data.get('pubisher')
    author=data.get('author')

    Book(name=name,price=price,category=category,pubishdata=pubishdata,pubisher=pubisher,author_id=author).save()
    allobj=Book.objects.filter()
    lis=[]
    for item in allobj:
        lis.append({
            'id':item.id,
            'name':item.name,
            'category':item.category,
            'pubishdata':item.pubishdata,
            'pubisher':item.pubisher,
            'author':item.author.name
        })
    return JsonResponse({
        'msg':"添加成功"
    })
# vue删除数据方法
@api_view(['DELETE'])
def delete_book_list(request,itemid):
    bookobj=Book.objects.get(id=itemid)
    bookobj.delete()
    allobj=Book.objects.filter()
    lis=[]
    for item in allobj:
        lis.append({
            'id':item.id,
            'name':item.name,
            'category':item.category,
            'pubishdata':item.pubishdata,
            'pubisher':item.pubisher,
            'author':item.author.name
        })
    return JsonResponse({
        'msg':"删除成功"
    })
# vue显示出要修改列表数据
@api_view(['GET'])
def getbookinfovue(request,itemid):
    obj=Book.objects.get(id=itemid)
    return JsonResponse({
        'name':obj.name,
        'price':obj.price,
        'category':obj.category,
        'pubishdata':obj.pubishdata,
        'pubisher':obj.pubisher,
        'author':obj.author.id,
    })
# vue修改列表数据
@api_view(['PUT'])
def updatebookvue(request,itemid):
    # 查询itemid查询出书籍的对象
    obj=Book.objects.get(id=itemid)
    dada=JSONParser().parse(request)

    name=dada.get('name')
    price=dada.get('price')
    category=dada.get('category')
    pubishdata=dada.get('pubishdata')
    pubisher=dada.get('pubisher')
    author=dada.get('author')

    obj.name=name
    obj.price=price
    obj.category=category
    obj.pubishdata=pubishdata
    obj.pubisher=pubisher
    obj.author_id=author

    obj.save()
    return JsonResponse({
        'msg':"修改成功"
    })

# 关联查询
@api_view(['GET'])
def getauthorbook(request):
    name=request.GET.get('name')
    # 根据姓名查询出作者对象
    obj=Author.objects.get(name=name)
    logger.logger.info(f"看看这个作者关联的对象:{obj.book.all()}")
    lis = []
    for itme in obj.book.all():
        lis.append({
            'authorname':obj.name,
            'authorgender':obj.gender,
            'authorage':obj.age,
            'authoraddress':obj.address,
            'bookname':itme.name,
            'bookprice':itme.price,
            'bookpubisher':itme.pubisher,


        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

# 关联查询（2）
@api_view(['GET'])
def getauthorbooktow(request):
    # name=request.GET.get('name')
    # # 根据姓名查询出作者对象
    # obj=Author.objects.get(name=name)
    # logger.logger.info(f"看看这个作者关联的对象:{obj.book.all()}")
    objs=Author.objects.filter()
    lis = []
    for obj in objs:
        for itme in obj.book.all():
            lis.append({
                'authorname':obj.name,
                'authorgender':obj.gender,
                'authorage':obj.age,
                'authoraddress':obj.address,
                'bookname':itme.name,
                'bookprice':itme.price,
                'bookcategory':itme.category,
                'bookpubishdata':itme.pubishdata,
                'bookpubisher':itme.pubisher,
                'bookcreaetime':itme.creaetime,
                'bookupdatetime':itme.updatetime,


        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

# 根据书名查作者
@api_view(['GET'])
def getbookautho(request):
    name=request.GET.get("name")
    obj=Book.objects.get(name=name)
    return JsonResponse({
        'name':obj.name,
        'price':obj.price,
        'category':obj.category,
        'authorname':obj.author.name,
        'authorgender':obj.author.gender,
        'authorage':obj.author.age,
        'authoraddress':obj.author.address,
    })



# 查询
@api_view(['GET'])
def getuserinfo(requect):
    # 调用鉴权的方法
    flag,name=checktoken(requect)
    if flag is False:
        return JsonResponse({
            'msg':"未登录，请先登录"
        },status=401)

    # 查询出所有的数据对象
    allobj=User.objects.filter()
    logger.logger.info(f"看看得到的说有数据对象:{allobj}")
    # 定义一个空列表用于存数
    lis=[]
    # 用一个for循环，把所有数据添加到lis中
    for item in allobj:
        lis.append({
            "姓名":item.name,
            "密码":item.password,
            "性别":item.gender,
            "年龄":item.age
        })
    return JsonResponse({
        "msg":"查询成功",
        "data":lis
    })


# 分页查询的方法
@api_view(['GET'])
def getpageuserinfo(request):
    # 调用鉴权的方法
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg':"未登录，请先登录"
        },status=401)
    # 得到页码
    page=request.GET.get('page')
    # 得到每页显示的数据条数
    pagesize=request.GET.get('pagesize')
    # 得到所有的数据
    allobj=User.objects.filter()
    # 生成一个分页的对象
    pageobj=Paginator(allobj,pagesize)
    # 用一个异常处理
    try:
        singleobj=pageobj.page(page)
    except PageNotAnInteger:
        singleobj=pageobj.page(1)
    except EmptyPage:
        singleobj=pageobj.page(pageobj.num_pages)

    # 定义一个空列表用于存数
    lis=[]
    logger.logger.info(f"看看这个数据singleobj.object_list长什么样子:{singleobj.object_list}")
    logger.logger.info(f"看看这个数据singleobj长什么样子:{singleobj}")
    for item in singleobj.object_list:
        lis.append({
            "name":item.name,
            "password":item.password,
            "gender":item.gender,
            "age":item.age,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })
@api_view(['GET'])
def getbookcheckfilte(request):
    obj=Book.objects.filter(id=1)

    logger.logger.info(f'看看查询出来的数据{obj}')
    return JsonResponse({
        # 'name':objs.name,
        # 'price':objs.price,
        # 'category':objs.category,
        # 'pubishdata':objs.pubishdata,
        'msg':"验证"
    })

# 完全匹配的查询
@api_view(['GET'])
def getbookcontentwm(request):
    name=request.GET.get('name')

    objs=Book.objects.get(name=name)
    return JsonResponse({
        'name':objs.name,
        'price':objs.price,
        'category':objs.category,
        'pubishdata':objs.pubishdata,
    })
# 从前端获取查询条件
@api_view(['GET'])
def getbookcondition(request):
    name=request.GET.get('name')
    price=request.GET.get('price')
    category=request.GET.get('category')
    pubisher=request.GET.get('pubisher')
    # 定义一个空字典
    dic={}
    if is_empty(name) is False:
        dic['name__contains']=name
    if is_empty(price) is False:
        dic['price__gte']=price
    if is_empty(category) is False:
        dic['category']=category
    if is_empty(pubisher) is False:
        dic['pubisher']=pubisher

    allobj=Book.objects.filter(**dic)

    lis=[]
    for item in allobj:
        lis.append({
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'pubishdata':item.pubishdata,
            'pubisher':item.pubisher,
            'authorname':item.author.name
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

# 模糊的查询
@api_view(['GET'])
def getbookcontent(request):
    name=request.GET.get('name')

    objs=Book.objects.filter(name__contains=name)
    lis=[]
    for item in objs:
        lis.append({
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'pubishdata':item.pubishdata,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

# 在什么日期之前查询的数据
@api_view(['GET'])
def getbookcontentpu(request):
    startdate=request.GET.get('startdate')
    enddate=request.GET.get('enddate')

    objs=Book.objects.filter(pubishdata__gte=startdate,pubishdata__lte=enddate)
    lis=[]
    for item in objs:
        lis.append({
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'pubishdata':item.pubishdata,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

# 或关系查询数据
@api_view(['GET'])
def getbookinfobycondintion(request):
    name=request.GET.get('name')
    price=request.GET.get('price')

    allobj=Book.objects.filter(Q(name=name) | (Q(price=price)))
    lis=[]
    for item in allobj:
        lis.append({
            'name':item.name,
            'price':item.price,
            'category':item.category,
            'pubishdata':item.pubishdata,
            "authorname":item.author.name
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })
# 分组查询
@api_view(['GET'])
def groubyselect(request):
    data=Book.objects.values('pubisher').annotate(maxprice=Max('price'),minprice=Min('price'),avgprice=Avg('price'),totalprice=Sum('price'),nums=Count('id'))
    logger.logger.info(f'看看data数据:{data}')

    lis=[]

    for item in data:
        # 使用get或format的两种小数点方式
        lis.append({
            '出版色的名字': item.get('pubisher'),
            '价格最大值': '{:.2f}'.format(item.get('maxprice')),
            '价格最小值': '%.2f' % item.get('minprice'),
            '价格平均值': '%.2f' % item.get('avgprice'),
            '价格总数': '%.2f' % item.get('totalprice'),
            '出版书籍数量': '%.2f' % item.get('nums'),
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })



# 修改
@api_view(['PUT'])
def modifyuser(requect):

    flag,name=checktoken(requect)
    if flag is False:
        return JsonResponse({
            'msg':"未登录"
        })

    data=JSONParser().parse(requect)
    userid=data.get('userid')
    logger.logger.info(f"看看userid得到的值：{userid}")
    name=data.get('name')
    password=data.get('password')
    gender=data.get('gender')
    age=data.get('age')
    # 定义一个空字典
    d={}
    if is_empty(userid):
        return JsonResponse({
            'msg':"用户id不可为空"
        })
    # 根据userid查询出数据对象
    obj=User.objects.get(id=userid)
    logger.logger.info(f"看看查询出来的单个数据对象:{obj}")

    # 如果name不为空就能修改
    if is_empty(name) is False:
        obj.name=name
    # 如果password不为空就能修改
    if is_empty(password) is False:
        obj.password=password
    # 如果gender不为空就能修改
    if is_empty(gender) is False:
        obj.gender=gender
    # 如果age不为空就能修改
    if is_empty(age) is False:
        obj.age=age

    # 进行保存:
    obj.save()
    # 返回修改后的内容
    return JsonResponse({
        'msg':"修改后的数据:",
        "name":obj.name,
        "password":obj.password,
        "gender":obj.gender,
        "age":obj.age,
    })

# 单个修改
@api_view(['PUT'])
def updatebook(request):
    data=JSONParser().parse(request)
    id=data.get('bookid')
    name=data.get('name')
    price=data.get('price')
    category=data.get('category')
    pubisher=data.get('pubisher')

    try:
        if is_empty(id):
            return JsonResponse({
                'msg':"书籍id不可为空"
            })
        obj=Book.objects.get(id=id)
    except:
        return JsonResponse({
            'msg':"服务器内部错误"
        },status=500)
    if is_empty(name) is False:
        if Book.objects.filter(name=name).exists():
            return JsonResponse({
                'msg':"书名已存在"
            },status=400)
        obj.name=name
    if is_empty(price) is False:
        obj.price=price
    if is_empty(category) is False:
        obj.category=category
    if is_empty(pubisher) is False:
        obj.pubisher=pubisher
    # 保存修改的数据
    obj.save()

    return JsonResponse({
        'msg':"修改成功",
    })


# 删除的方法
@api_view(['DELETE'])
def deleteuser(requect):
    data=JSONParser().parse(requect)
    userid=data.get("userid")
    if is_empty(userid):
        return JsonResponse({
            "msg":"用户id不能为空"
        },status=400)
    obj=User.objects.get(id=userid)
    obj.delete()
    return JsonResponse({
        "mag":"删除成功"
    },status=200)

# 班级学生多对多关联
# 添加学生信息
@api_view(['POST'])
def add_Student(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    age=data.get('age')

    Student(name=name,age=age).save()

    return JsonResponse({
        'msg':"添加学生成功"
    })

# 添加课程
@api_view(['POST'])
def add_course(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    time=data.get('time')
    stuents=data.get('stuents')

    stuents=Student.objects.get(id=stuents)

    if Course.objects.filter(name=name).exists():
        courseobj = Course.objects.get(name=name)
    else:
        Course(name=name,time=time).save()
        courseobj=Course.objects.get(name=name)
    # 想课程对象里添加学生对象
    courseobj.stuents.add(stuents)

    return JsonResponse({
        'msg':"添加课程成功"
    })
# 查询
@api_view(['GET'])
def getstudentcourse(request):
    name=request.GET.get('name')

    studentobj=Student.objects.get(name=name)

    courseobjs=studentobj.course.all()

    lis=[]
    for item in courseobjs:
        lis.append({
            '学生名':name,
            '选修课程':item.name,
            '选修课时':item.time,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })
# # 查询
@api_view(['GET'])
def getstudentcourse(request):
    name=request.GET.get('name')

    studentobj=Course.objects.get(name=name)

    courseobjs=Course.studentobj.all()

    lis=[]
    for item in courseobjs:
        lis.append({
            '学生名':name,
            '选修课程':item.name,
            '大约称':item.time,
        })
    return JsonResponse({
        'msg':"查询成功",
        'data':lis
    })

@api_view(['POST'])
def addc(request):
    data=JSONParser().parse(request)

    name=data.get('name')
    time=data.get('time')
    stuents=data.get('stuents')

    stuents=Student.objects.get(id=stuents)

    if Course.objects.filter(name=name).exists():
        obj=Course.objects.get(name=name)
    else:
        Course(name=name,time=time).save()
        obj=Course.objects.get(name=name)
    obj.stuents.add(stuents)

    return JsonResponse({
        'msg':"自己添加成功"
    })





